package com.joey.concurrency.example.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author hyy
 **/
@Slf4j
public class ConditionExample {

    /**
     * 过程描述
     * 线程1首先reentrantLock.lock()，由于condition.await()释放锁，
     * 线程2判断并获取reentrantLock.lock(),Thread.sleep(3000);
     * condition.signalAll()发送信号，线程1进入等待队列，由于对象还处于锁状态，
     * reentrantLock.unlock();线程2释放锁，线程1接着执行。
     * @param args
     */
    public static void main(String[] args) {
        ReentrantLock reentrantLock = new ReentrantLock();
        Condition condition = reentrantLock.newCondition();

        new Thread(() -> {
            try {
                reentrantLock.lock();
                log.info("wait signal"); // 1
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("get signal"); // 4
            reentrantLock.unlock();
        }).start();

        new Thread(() -> {
            reentrantLock.lock();
            log.info("get lock"); // 2
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            condition.signalAll();
            log.info("send signal ~ "); // 3
            reentrantLock.unlock();
        }).start();
    }
}
